package cn.iocoder.yudao.module.reading.controller.admin.bookset;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.reading.controller.admin.bookset.vo.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.bookset.BookSetDO;
import cn.iocoder.yudao.module.reading.service.bookset.BookSetService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 绘本集管理
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 绘本集管理")
@RestController
@RequestMapping("/reading/admin/book-sets")
@Validated
@Slf4j
public class AdminBookSetController {

    @Resource
    private BookSetService bookSetService;
    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    /**
     * 检查当前用户是否为管理员
     * 绘本集管理只允许管理员操作
     */
    private void checkAdminPermission() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(401, "用户未登录");
        }
        if (!UserTypeEnum.ADMIN.getValue().equals(loginUser.getUserType())) {
            throw new ServiceException(403, "权限不足，只有管理员可以管理绘本集");
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建绘本集")
    @PreAuthenticated
    public CommonResult<Long> createBookSet(@Valid @RequestBody BookSetCreateReqVO createReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("创建绘本集，标题: {}, 语言: {}, 分类ID: {}",
                createReqVO.getTitle(), createReqVO.getLanguage(), createReqVO.getCategoryId());

        Long bookSetId = bookSetService.createBookSet(createReqVO);

        log.info("绘本集创建成功，ID: {}", bookSetId);
        return success(bookSetId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新绘本集")
    @PreAuthenticated
    public CommonResult<Boolean> updateBookSet(@Valid @RequestBody BookSetUpdateReqVO updateReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("更新绘本集，ID: {}, 标题: {}", updateReqVO.getId(), updateReqVO.getTitle());

        bookSetService.updateBookSet(updateReqVO);

        log.info("绘本集更新成功，ID: {}", updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除绘本集")
    @PreAuthenticated
    public CommonResult<Boolean> deleteBookSet(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("删除绘本集，ID: {}", id);

        bookSetService.deleteBookSet(id);

        log.info("绘本集删除成功，ID: {}", id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得绘本集")
    @Parameter(name = "id", description = "绘本集编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<BookSetAdminRespVO> getBookSet(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        BookSetDO bookSet = bookSetService.getBookSet(id);
        BookSetAdminRespVO result = BeanUtils.toBean(bookSet, BookSetAdminRespVO.class);

        // 转换封面URL为完整URL
        if (result.getCover() != null) {
            result.setCover(staticResourceUrlUtils.toFullUrl(result.getCover()));
        }

        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得绘本集分页")
    @PreAuthenticated
    public CommonResult<PageResult<BookSetAdminRespVO>> getBookSetPage(@Valid BookSetPageReqVO pageReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        PageResult<BookSetDO> pageResult = bookSetService.getBookSetPage(pageReqVO);
        PageResult<BookSetAdminRespVO> result = BeanUtils.toBean(pageResult, BookSetAdminRespVO.class, respVO -> {
            // 转换封面URL为完整URL
            if (respVO.getCover() != null) {
                respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
            }
        });
        return success(result);
    }

    @GetMapping("/next-id")
    @Operation(summary = "获取下一个绘本集ID")
    @PreAuthenticated
    public CommonResult<Long> getNextBookSetId() {
        // 检查管理员权限
        checkAdminPermission();

        log.info("获取下一个绘本集ID");

        Long nextId = bookSetService.getNextBookSetId();

        log.info("下一个绘本集ID: {}", nextId);
        return success(nextId);
    }

    @PutMapping("/{bookSetId}/update-book-count")
    @Operation(summary = "更新绘本集的绘本数量")
    @PreAuthenticated
    public CommonResult<Boolean> updateBookSetBookCount(@PathVariable("bookSetId") Long bookSetId) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("更新绘本集绘本数量，绘本集ID: {}", bookSetId);

        bookSetService.updateBookSetBookCount(bookSetId);

        log.info("绘本集绘本数量更新成功，绘本集ID: {}", bookSetId);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获得绘本集列表")
    @PreAuthenticated
    public CommonResult<List<BookSetAdminRespVO>> getBookSetList(
            @Parameter(description = "语言类型") @RequestParam(value = "language", required = false) String language,
            @Parameter(description = "标题") @RequestParam(value = "title", required = false) String title) {
        checkAdminPermission();

        List<BookSetDO> list = bookSetService.getBookSetList(language, title);
        List<BookSetAdminRespVO> result = BeanUtils.toBean(list, BookSetAdminRespVO.class, respVO -> {
            // 转换封面URL为完整URL
            if (respVO.getCover() != null) {
                respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
            }
        });
        return success(result);
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除绘本集")
    @PreAuthenticated
    public CommonResult<Boolean> batchDeleteBookSet(@RequestBody @Valid BookSetBatchDeleteReqVO batchDeleteReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("批量删除绘本集，数量: {}", batchDeleteReqVO.getIds().size());

        bookSetService.batchDeleteBookSet(batchDeleteReqVO.getIds());

        log.info("批量删除绘本集成功，数量: {}", batchDeleteReqVO.getIds().size());
        return success(true);
    }

    @PutMapping("/batch-update-status")
    @Operation(summary = "批量更新绘本集状态")
    @PreAuthenticated
    public CommonResult<Boolean> batchUpdateBookSetStatus(@RequestBody @Valid BookSetBatchUpdateStatusReqVO batchUpdateReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("批量更新绘本集状态，数量: {}, 状态: {}", batchUpdateReqVO.getIds().size(), batchUpdateReqVO.getIsActive());

        bookSetService.batchUpdateBookSetStatus(batchUpdateReqVO.getIds(), batchUpdateReqVO.getIsActive());

        log.info("批量更新绘本集状态成功，数量: {}", batchUpdateReqVO.getIds().size());
        return success(true);
    }

}
